﻿package com.firefighting.util;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ImageUploadUtil {
/*
 * 编写图片上传、文件上传的工具类
 */
	
	public static boolean getImageFromClient(String imageName, String dir, HttpServletRequest request, HttpServletResponse response, InputStream in){

		//上传的图片格式必为jpg
		boolean status = false;
		
		try{
		
			String basePath=request.getSession().getServletContext().getRealPath("/"+dir);//得到工程目录，在servelet中取得路径
			File path_file = new File(basePath);
	        if (!path_file.exists()){
	        	path_file.mkdirs();
	        }
			String imagePath=basePath+File.separator+imageName;
			System.out.println("imagePath="+imagePath);
			File imageFile=new File(imagePath);
			if(!imageFile.exists()){
				imageFile.createNewFile();
			}
			OutputStream fileOut=new FileOutputStream(imageFile);
			
			byte[] buffer=new byte[1024*8];
			int length=0;
			int count=0;
			while((length=in.read(buffer))!=-1){
				fileOut.write(buffer, 0, length);
				count+=length;
			}
			fileOut.flush();
			fileOut.close();
			status = true;
			System.out.println("上传成功");
			
			//复制图片
			Properties prop = new Properties();
			InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("savefile.properties");
			try {
				prop.load(is);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			String copyToImageDirPaht = prop.getProperty("toImageDir");
			System.out.println("copyToImageDirPaht:" + copyToImageDirPaht);
			
			File fromFile = new File(imagePath);
			System.out.println("fromFile:" + fromFile.getAbsolutePath());
			
			String toFile_path = copyToImageDirPaht+File.separator+dir;
			File toFile_dir = new File(toFile_path);
	        if (!toFile_dir.exists()){
	        	toFile_dir.mkdirs();
	        }
	        
			File toFile = new File(toFile_path+File.separator+imageName);
			System.out.println("toFile:" + toFile.getAbsolutePath());
			copyFile(fromFile, toFile);
	    }
		catch(Exception e){
			e.printStackTrace();
			System.out.print("上传失败");
			status = false;
			in.close();
		}
		finally{
			return status;
		}
	}

	private static void copyFile(File fromFile, File toFile) throws IOException {
		FileInputStream ins = new FileInputStream(fromFile);
		FileOutputStream out = new FileOutputStream(toFile);
		byte[] b = new byte[1024];
		int n = 0;
		while ((n = ins.read(b)) != -1) {
			out.write(b, 0, b.length);
		}

		ins.close();
		out.close();
	}
}
